<template>
  <div>
    <TableSearch
      :query="query"
      :options="searchOpt"
      :search="handleSearch"
      @reset-search="handleresetSearch"
    >
      <template #coverUrl>
        <div>1111-------------</div>
      </template>
      <template #parent>
        <el-cascader
          v-model="query.tagIdList"
          :options="cascaderOptions"
          :props="{ checkStrictly: true, multiple: true }"
          @change="handleChangeSeach"
          clearable
          placeholder="请选择歌单标签"
        />
      </template>
    </TableSearch>
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :currentPage="page.currPage"
        :viewFunc="handleView"
        :delFunc="handleDelete"
        :change-page="changePage"
        :editFunc="handleEdit"
        :upFunc="handleUpPlayList"
        :downFunc="handleDownPlayList"
        :viewSongFunc="handleViewSongFunc"
      >
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd"
            >新增</el-button
          >
        </template>
        <template #coverUrl="{ rows }">
          <el-image :src="rows.coverUrl" fit="cover" class="avatar"></el-image>
        </template>
        <template #isRecommended="{ rows }">
          <div v-if="rows.isRecommended === 1">推荐</div>
          <div v-else-if="rows.isRecommended === 0">不推荐</div>
        </template>
        <template #isOffline="{ rows }">
          <el-tag type="success" v-if="rows.isOffline === 0">上架</el-tag>
          <el-tag type="danger" v-else>下架</el-tag>
        </template>
      </TableCustom>
    </div>
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      v-model="visible"
      width="700px"
      destroy-on-close
      :close-on-click-modal="closeDialog"
      @close="closeDialog"
    >
      <TableEdit
        :form-data="rowData"
        :options="options"
        :edit="isEdit"
        :update="updateData"
        @closeDialogP="closeDialog"
      >
        <template #parent>
          <el-cascader
            v-model="selectParentTagId"
            :options="cascaderOptions"
            :props="{ checkStrictly: true, multiple: true }"
            clearable
            placeholder="请选择歌单标签"
          />
        </template>
      </TableEdit>
    </el-dialog>
    <el-dialog title="详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail :data="viewData" @closeDialogP="visible1 = false">
        <template #coverUrl="{ rows }">
          <el-image :src="rows.coverUrl" fit="cover" class="avatar"></el-image>
        </template>
        <template #playlistType="{ rows }">
          <div v-if="rows.playlistType === 1">系统</div>
          <div v-else-if="rows.playlistType === 2">自建</div>
        </template>
        <template #isRecommended="{ rows }">
          <div v-if="rows.isRecommended === 1">推荐</div>
          <div v-else-if="rows.isRecommended === 0">不推荐</div>
        </template>
        <template #isOffline="{ rows }">
          <el-tag type="success" v-if="rows.isOffline === 0">上架</el-tag>
          <el-tag type="danger" v-else>下架</el-tag>
        </template>
      </TableDetail>
    </el-dialog>
    <!-- 歌单下面的歌曲列表 -->
    <el-drawer
      v-model="drawer2"
      direction="rtl"
      title="歌曲列表"
      :before-close="handleClose"
      append-to-body
      size="60%"
    >
      <MusicLibraryList
        ref="childRef2"
        :isDrawer="drawer2"
        :playListId="playListIdSelect"
        @parentEvent="getData"
      ></MusicLibraryList>
    </el-drawer>
  </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { CirclePlusFilled } from "@element-plus/icons-vue";
import { PlayList } from "@/types/playList";
import {
  fetchPlaylistData,
  fetchPlaylistCreate,
  fetchDeletePlaylist,
  fetchSoldInPlaylist,
  fetchSoldOutPlaylist,
} from "@/api/playList";
import {
  fetchPlaylistTagTreeData,
  fetchPlaylistCategoryData,
} from "@/api/configuration";
import TableCustom from "@/components/table-custom.vue";
import TableDetail from "@/components/table-detail.vue";
import TableSearch from "@/components/table-search.vue";
import { FormOption, FormOptionList } from "@/types/form-option";
import MusicLibraryList from "@/views/playList/musicLibraryList.vue";
import { get } from "@vueuse/core";

// 搜索栏
// 查询相关
const query = reactive({
  keyword: "",
  categoryIdList: [], //分类id
  isRecommended: "", //是否推荐：0-不推荐，1-推荐
  tagIdList: [], //标签id
});
const selectParentTagId_search = ref([]); //搜索条件的标签id
const handleChangeSeach = (value) => {
  const tagIdListFi = ref([]);
  console.log("头部--搜索条件--选择标签");
  console.log(query.tagIdList);
  if (query.tagIdList && query.tagIdList.length > 0) {
    query.tagIdList.forEach((item, index) => {
      console.log("走-1");
      console.log(item);
      tagIdListFi.value.push(item[item.length - 1]);
    });
  }
  query.tagIdList = tagIdListFi.value;
  getData();
};

const handleresetSearch = () => {
  query.tagIdList = [];
  getData();
};

const handleSearch = () => {
  changePage(1);
};

// 表格相关
let columns = ref([
  { type: "index", label: "序号", width: 55, align: "center" },
  { prop: "playlistName", label: "歌单名称", width: 150 },
  { prop: "description", label: "歌单描述", width: 400 },
  { prop: "songCount", label: "歌曲数量", width: 150 },
  // { prop: "coverUrl", label: "歌单封面", width: 150 },
  { prop: "tagNameList", label: "歌单标签", width: 150 },
  { prop: "categoryNameList", label: "歌单分类", width: 150 },
  { prop: "playlistType", label: "歌单类型", width: 150 },
  { prop: "isRecommended", label: "是否推荐", width: 150 }, //0-不推荐，1-推荐
  { prop: "isOffline", label: "是否下架", width: 150 }, //是否下架：0-否，1-是
  { prop: "createTime", label: "创建时间" },
  { prop: "operator", label: "操作", width: 300, fixed: "right" },
]);

// 请求表格数据参数
const page = reactive({
  currPage: 1,
  size: 10,
  total: 0,
});
const tableData = ref([]);
// 获取歌曲列表数据
const getData = async () => {
  let obj_1 = {
    currPage: page.currPage,
    size: page.size,
    playlistType: 1, //歌单类型 1-歌单中心(系统歌单) 2-我的歌单（自建和收藏的所有歌单） 3-收藏的系统歌单 4-收藏的自建歌单 99-所有
  };
  let params = { ...query, ...obj_1 };
  const res = await fetchPlaylistData(params);
  let list = res.data.data.records;
  let obj = {};
  if (list.length > 0) {
    list.forEach((item) => {
      if (Array.isArray(item.categoryNameList)) {
        item.categoryNameList = item.categoryNameList.join(",");
      }
      if (Array.isArray(item.tagNameList)) {
        item.tagNameList = item.tagNameList.join(",");
      }
    });
  }
  tableData.value = res.data.data.records;
  page.total = res.data.data.total;
};
getData();

const menuData = ref([]);
const cascaderOptions = ref([]);
const getOptions = (data: any) => {
  return data.map((item) => {
    const a: any = {
      label: item.tagName,
      value: item.playlistTagId,
      tagLevel: item.tagLevel,
      playlistCount: item.playlistCount,
      remark: item.remark,
      parentTagId: item.parentTagId,
    };
    if (item.playlistTagList) {
      a.children = getOptions(item.playlistTagList);
    }
    return a;
  });
};
// 获取-歌单标签树
const getPlaylistTag = async () => {
  let params = {
    isShowNoCount: 1, //是否显示没有歌曲的标签 0-否 1-是
  };
  const res = await fetchPlaylistTagTreeData(params);
  console.log("获取歌单标签树");
  console.log(res.data);
  menuData.value = res.data.data;
  console.log(menuData.value);
  // page.total = res.data.data.total;
  // console.log(page.total);
  cascaderOptions.value = getOptions(menuData.value);
  console.log("11111");
  console.log(cascaderOptions.value);
};
getPlaylistTag();

let options = ref({}); //新增和编辑框
let searchOpt = ref([]); //搜索栏
const categoryList = ref([]); //歌单分类选项列表
// 获取-歌单分类选项列表
const getCategoryList = async () => {
  let params = {
    currPage: 1,
    size: 1000,
    isShowNoCount: 1,
  };
  const res = await fetchPlaylistCategoryData(params);

  let list = res.data.data.records;
  list.forEach((item) => {
    item.value = item.playlistCategoryId;
    item.label = item.categoryName;
  });
  categoryList.value = list;
  console.log("歌单分类管理");
  console.log(categoryList.value);
  //新增和编辑框
  options.value = {
    labelWidth: "82px",
    span: 24,
    list: [
      {
        type: "input",
        label: "歌单名称",
        prop: "playlistName",
        required: true,
        placeholder: "请输入歌单名称",
      },
      {
        type: "input",
        label: "歌单描述",
        prop: "description",
        placeholder: "请输入歌单描述",
      },
      {
        type: "select",
        label: "歌单类型",
        prop: "playlistType",
        opts: [{ label: "系统", value: 1 }],
        placeholder: "请选择歌单类型",
      }, //0-无 1-系统 2-自建
      {
        type: "parent",
        label: "歌单标签",
        prop: "parent",
        placeholder: "请输入歌单标签",
      },
      {
        type: "select",
        label: "歌单分类",
        prop: "categoryIdList",
        multiple: true,
        opts: categoryList.value,
        placeholder: "请选择歌单分类",
      },
      {
        type: "switch",
        label: "是否推荐",
        prop: "isRecommended",
        activeValue: 1,
        inactiveValue: 0,
        activeText: "推荐",
        inactiveText: "不推荐",
      },
      {
        type: "upload",
        label: "歌单封面(请上传jpg，gif，png等图片格式)",
        prop: "coverUrl",
      }, //coverUrl
    ],
  };
  // 搜索栏
  searchOpt.value = [
    {
      type: "input",
      label: "歌单名称：",
      prop: "keyword",
      placeholder: "请输入歌单名称",
    },
    {
      type: "parent",
      label: "歌单标签：",
      prop: "parent",
      placeholder: "请输入歌单标签",
    },
    {
      type: "select",
      label: "歌单分类：",
      prop: "categoryIdList",
      multiple: true,
      opts: categoryList.value,
      placeholder: "请选择歌单分类",
    },
    {
      type: "select",
      label: "是否推荐：",
      prop: "isRecommended",
      opts: [
        { label: "无", value: "" },
        { label: "推荐", value: 1 },
        { label: "不推荐", value: 0 },
      ],
    },
    // {
    //   type: "switch",
    //   label: "是否推荐",
    //   prop: "isRecommended",
    //   activeValue: 1,
    //   inactiveValue: 0,
    //   activeText: "推荐",
    //   inactiveText: "不推荐",
    // },
  ];
};
getCategoryList();

// 分页
const changePage = (val: number) => {
  console.log("点击分页");
  page.currPage = val;
  console.log(page.currPage);
  getData();
};

// 新增/编辑弹窗相关

const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const selectParentTagId = ref([]);

// 歌区歌曲（每个歌单的歌曲）
const drawer2 = ref(false);
const handleClose = (done: () => void) => {
  done();
};

const playListIdSelect = ref(""); //选择的歌单id
const childRef2 = ref(null);
const handleViewSongFunc = (row) => {
  drawer2.value = true;
  console.log("点击具体的某一个歌单");
  console.log(row);
  playListIdSelect.value = row.playlistId;
  setTimeout(() => {
    if (childRef2.value) {
      childRef2.value.getData();
    }
  }, 100);
};

// 新增
const handleAdd = (row) => {
  console.log("新增");
  selectParentTagId.value = [];
  rowData.value = { ...row };
  console.log(rowData.value);
  isEdit.value = false;
  visible.value = true;
};

// 编辑
const handleEdit = (row: PlayList) => {
  console.log("编辑");
  row.thumb = row.coverUrl;
  rowData.value = { ...row };
  selectParentTagId.value = row.tagIdList;
  console.log(rowData.value);
  isEdit.value = true;
  visible.value = true;
};

const updateData = async (data) => {
  console.log("编辑或者新增");
  console.log(data);
  console.log(selectParentTagId.value);
  let parentTagId = [];
  if (
    selectParentTagId.value &&
    Array.isArray(selectParentTagId.value) &&
    selectParentTagId.value.length > 0
  ) {
    selectParentTagId.value.forEach((item, index) => {
      console.log("走-1");
      console.log(item);
      // parentTagId.push(item[item.length - 1]);
      if (Array.isArray(item)) {
        parentTagId.push(item[item.length - 1]);
        // parentTagId.push(item[0]);
      } else {
        parentTagId.push(item);
      }
    });
  } else if (
    selectParentTagId.value &&
    typeof selectParentTagId.value === "string"
  ) {
    console.log("不处理");
  } else {
    parentTagId = [];
  }
  console.log("最终的歌单标签id是什么");
  console.log(parentTagId);
  let datas = {};
  let obj = {
    tagIdList: parentTagId,
  };
  delete data.tagNameList;
  delete data.categoryNameList;
  let editObi = { playlistId: data.playlistId };
  if (isEdit.value) {
    datas = { ...data, ...obj, ...editObi };
  } else {
    datas = { ...data, ...obj };
  }
  console.log("创建/修改歌单---参数");
  console.log(datas);
  const res = await fetchPlaylistCreate(datas);
  console.log("创建/修改歌单");
  console.log(res.data);
  if (res.data.code === 0) {
    ElMessage.success("成功");
    setTimeout(() => {
      getData();
    }, 1000);
  } else {
    ElMessage.error(res.data.msg);
  }

  closeDialog();
};

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

// 详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: [],
});
const handleView = (row) => {
  viewData.value.row = { ...row };
  viewData.value.list = [
    {
      prop: "playlistName",
      label: "歌单名称",
    },
    {
      prop: "description",
      label: "歌单描述",
    },
    {
      prop: "songCount",
      label: "歌曲数量",
    },
    {
      prop: "coverUrl",
      label: "歌单封面",
    },
    {
      prop: "tagNameList",
      label: "歌单标签",
    },
    {
      prop: "categoryNameList",
      label: "歌单分类",
    },
    {
      prop: "playlistType",
      label: "歌单类型",
    },
    {
      prop: "isRecommended",
      label: "是否推荐",
    },
    {
      prop: "isOffline",
      label: "是否下架",
    },
    {
      prop: "createTime",
      label: "创建时间",
    },
    {
      prop: "canModified",
      label: "能否编辑",
    },
  ];
  visible1.value = true;
};

// 删除歌单
const handleDelete = async (row) => {
  let datas = {
    id: row.playlistId,
  };
  const res = await fetchDeletePlaylist(datas);
  if (res.data.code == 0) {
    ElMessage.success("删除成功");
    getData();
  }
};

// 上架歌单
const handleUpPlayList = async (row) => {
  let arr = [];
  arr.push(row.playlistId);
  let datas = {
    playlistId: arr,
  };
  const res = await fetchSoldInPlaylist(datas);
  if (res.data.code == 0) {
    ElMessage.success("上架成功");
    getData();
  }
};

// 下架歌单
const handleDownPlayList = async (row) => {
  let arr = [];
  arr.push(row.playlistId);
  let datas = {
    playlistId: arr,
  };
  const res = await fetchSoldOutPlaylist(datas);
  if (res.data.code == 0) {
    ElMessage.success("下架成功");
    getData();
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .el-upload {
  width: 200px;
  height: 200px;
}
.avatar {
  width: 100px;
  height: 100px;
  margin: 0 auto;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
}
</style>
